package com.wsy.wsyojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.github.dockerjava.core.command.LogContainerResultCallback;
import com.wsy.wsyojcodesandbox.model.ExecuteCodeRequest;
import com.wsy.wsyojcodesandbox.model.ExecuteCodeResponse;
import com.wsy.wsyojcodesandbox.model.ExecuteMessage;
import com.wsy.wsyojcodesandbox.model.JudgeInfo;
import com.wsy.wsyojcodesandbox.utils.ProcessUtils;
import com.wsy.wsyojcodesandbox.utils.Trie;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Deprecated
public class JavaDockerCodeSandbox implements CodeSandBox {

    //默认存放文件夹名
    private static final String GLOBAL_CODE_DIR = "tempCode";

    //默认类名
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    //最大运行时间
    private static final long TIME_OUT = 5000L;

    //自定义安全管理器路径
    private static final String SECURITY_MANAGER_PATH =
            "E:\\JavaCodeSandbox\\src\\main\\resources\\security\\MySecurityManager.java";

    //自定义安全管理器类名
    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";

    //开关
    private static Boolean FIRST_INIT = true;

    private static final Object lock;

    //静态代码块初始化
    static {
//        TRIE = new Trie(blackList);
        lock = new Object();
    }

    public static void main(String[] args) {
        JavaDockerCodeSandbox javaNativeCodeSandbox = new JavaDockerCodeSandbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "1 3"));
        //正常
//        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);

        //异常问题
        String code = ResourceUtil.readStr("testCode/unSafeCode/ReadFileErr.java", StandardCharsets.UTF_8);

        //Scanner输入
//        String code = ResourceUtil.readStr("testCode/simpleCompute/Main.java", StandardCharsets.UTF_8);

        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");

        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }

    /**
     * 从提交的请求体中读代码，存放到本地文件，进行编译
     * @param executeCodeRequest
     * @return
     */
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        //准备watch，后续开始执行代码时监控执行时间
        StopWatch stopWatch = new StopWatch();

        //从request对象得到执行信息
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        //检查是否包含敏感词, Docker 隔离时暂不需要
//        WordTree wordTree = new WordTree();
//        String found = TRIE.containsBlacklistWord(code);
//        if(found != null) {
//            System.out.println("找到了:" + found);
//            return getResp(new RuntimeException("敏感词检测..."));
//        }

        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR;
        //判断全局代码目录是否存在，没有就新建
        if(!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        //1. 用户代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //2. 编译代码得到.class
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcess(compileProcess, "compile");
            System.out.println(executeMessage);
        } catch (Exception e) {
            return getResp(e);
        }

        //3. 创建容器，上传编译代码到容器内
        //默认DockerClient, 创建Docker交互进程
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String image = "openjdk:8-alpine";

//        异步拉取镜像
        synchronized (lock) {
            if (FIRST_INIT) {
                PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
                PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                    @Override
                    public void onNext(PullResponseItem item) {
                        System.out.println("下载镜像..." + item.getStatus());
                        super.onNext(item);
                    }
                };
                try {
                    pullImageCmd
                            .exec(pullImageResultCallback)
                            .awaitCompletion();
                } catch (InterruptedException e) {
                    System.out.println("拉取镜像异常！");
                    throw new RuntimeException(e);
                }
                System.out.println("下载完成");
                FIRST_INIT = false;
            }
        }

        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        //创建时就指定本地文件同步(映射、挂载)到容器中的某个位置
        HostConfig hostConfig = new HostConfig();
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
        hostConfig.withMemory(100 * 1000 * 1000L); //给容器设置100M内存，实现内存控制
        hostConfig.withCpuCount(1L);

        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withAttachStderr(true)
                .withTty(true)
                .withCmd("echo", "Hello Docker")
                .exec();
        System.out.println(createContainerResponse);
        //获取创建的容器id
        String containerId = createContainerResponse.getId();

        //启动刚刚创建的容器
        dockerClient.startContainerCmd(containerId).exec();
        //先保证让容器启动完毕后再去加载日志，不然因为异步的原因，可能日志先执行了
//        Thread.sleep(5000L);

        // docker exec {container name}(容器名) java -cp /app(刚刚挂载的目录下) Main 1 3
        //准备List接收每一个输入对应的返回信息
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String[] arg = inputArgs.split(" ");
            String[] cmdArr = ArrayUtil.append(new String[] {"java", "-cp", "/app", "Main"}, arg);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArr)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("执行命令为：" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errMessage = {null};
            //判断是否超时
            final boolean[] timeout = {true};
            //为异步执行代码定义一个回调函数，执行完后启动该类
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    //执行完程序后，执行最后这个方法
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if(StreamType.STDERR.equals(streamType)) {
                        errMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errMessage[0]);
                    }else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }
            };

            final long[] maxMemory = {0L};
            //获取占用的内存(周期，因为内存占用时时刻刻是不同的)
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onNext(Statistics statistics) {
                    System.out.println("内存占用: " + statistics.getMemoryStats().getUsage());
                    maxMemory[0] = Math.max(maxMemory[0], statistics.getMemoryStats().getUsage());
                }
                @Override
                public void onStart(Closeable closeable) {

                }
                @Override
                public void onError(Throwable throwable) {

                }
                @Override
                public void onComplete() {

                }
                @Override
                public void close() throws IOException {

                }
            });

            try {
                //开始计时
                stopWatch.start();

                //docker中执行代码, 因异步执行,必须加上awaitCompletion
                //等待执行完毕，去调用上面定义的回调函数
                dockerClient.execStartCmd(execCreateCmdResponse.getId())
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);

                //结束计时
                stopWatch.stop();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errMessage[0]);
            executeMessage.setTime(stopWatch.getLastTaskTimeMillis());
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();

        //4. 整理输出
        List<String> outputList = new ArrayList<>();
        //取最大运行时间？
        //可以改造成获取每一个测试用例的运行时间
        //内存同理
        long maxTime = 0L, maxMemory = 0L;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();

            if(StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long runtime = executeMessage.getTime();
            if(runtime != null) {
                maxTime = Math.max(maxTime, runtime);
            }

            Long memory = executeMessage.getMemory();
            if(memory != null) {
                maxMemory = Math.max(maxMemory, memory);
            }
        }
        if(outputList.size() == executeMessageList.size()) {
            //每条都正常输出，没有编译的问题
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        //怎么获取运行内存？ => Docker中可以用监控
        judgeInfo.setMemory(maxMemory);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        //5. 清理文件
        if(userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
        }

        return executeCodeResponse;
    }

    //6. 错误处理: 定义一个新的方法，返回沙箱出错信息。
    //返回沙箱出错时的信息
    private ExecuteCodeResponse getResp(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
